<template>
  <div class="follow-user-container">
    <van-button
      v-if="isFollowed"
      @click="onFollow"
      class="follow-btn"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      :loading="loading"
      >关注</van-button
    >
    <van-button
      v-else
      @click="onFollow"
      class="follow-btn"
      round
      size="small"
      :loading="loading"
      >已关注</van-button
    >
  </div>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'FollowUser',
  model: {
    prop: 'isFollowed',
    event: 'update-is_followed'
  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      loading: false // loading状态
    }
  },
  methods: {
    // onFollow () {
    //   this.isFollowed = !this.isFollowed
    // }
    async onFollow () {
      this.loading = true
      try {
        if (this.isFollowed) {
          //  取消关注
          await deleteFollow(this.userId)
        } else {
          await addFollow(this.userId)
        }
        // this.article.is_followed = !this.article.is_followed
        this.$emit('update-is_followed ', !this.isFollowed)
      } catch (err) {
        let message = '操作失败，请重试'
        console.log(err.response)
        if (err.response && err.response.status === 400) {
          message = '不能关注自己'
        }
        this.$toast(message)
      }
      this.loading = false
    }
  }
}
</script>

<style scoped lang="less"></style>
